package oas.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import oas.domain.User;

/**
 * 用户操作拦截器
 *
 * @author jtc
 * @version v1.1.0
 */
public class UserInterceptor implements HandlerInterceptor {

    private final static Log log = LogFactory.getLog(UserInterceptor.class);

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub

    }

    /**
     * 检测用户是否登录，未登录不能访问相关界面
     * <p>
     * preHandle会在一个控制器类的处理方法被调用之前执行此方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        log.debug("1.ManagerInerceptor-Called before handler method");
        // 获取session
        HttpSession session = request.getSession();
        String url = (request.getRequestURI());
        ;
        System.out.println(url);
        User user = (User) session.getAttribute("user");
        if (user != null && user.getRole().equals("User") || user != null && url.endsWith("center")
                || user != null && url.endsWith("update") || user != null && url.endsWith("password")) {
            return true;
        }
        // 不符合条件的转发到登录页面
        response.sendRedirect(request.getContextPath() + "/login");
        return false;
    }

}
